<!-- 证照管理 -->
<template>
  <div v-loading="loading" class="certificate-container">
    <CustomTabs :tabList="classNameList" :activeName="classCode" @tabSelect="handelTabSelected" />
    <div class="mg-b-8">
      <div class="tab">
        <div v-for="item in tabList" :key="item.id" :class="['tab-item', { 'active-tab': activeTab?.id === item?.id }]" @click="changeTab(item)">
          {{ item?.name }}
        </div>
      </div>
    </div>
    <div class="flex-center">
      <px-form ref="formRef" :model="queryParams" :inline="true" class="custom-form-ui search-form">
        <px-form-item label="证照类型" prop="twoCode">
          <px-select v-model="queryParams.twoCode" style="width: 260px" placeholder="请选择证照分类" clearable @change="handleTypeChange">
            <px-option v-for="item in classificationList" :key="item.id" :label="item.name" :value="item.singleCode" />
          </px-select>
        </px-form-item>
        <px-form-item label="证照名称" prop="threeCode">
          <px-select v-model="queryParams.threeCode" style="width: 260px" placeholder="请选择证照名称" clearable>
            <px-option v-for="item in nameList" :key="item.id" :label="item.name" :value="item.singleCode" />
          </px-select>
        </px-form-item>
        <px-form-item label="状态" prop="status">
          <px-select v-model="queryParams.status" style="width: 260px" placeholder="请选择状态" clearable>
            <px-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value" />
          </px-select>
        </px-form-item>
        <div class="search-form-btn">
          <px-button type="primary" @click="handleQuery">查询</px-button>
          <px-button @click="resetQuery">重置</px-button>
        </div>
      </px-form>
    </div>
    <div class="flex-center mg-b-8">
      <px-button v-has="'ALL_KNOWLEDGE_CERTIFICATEMANAGE_CERTIFICATE_ADD'" type="primary" @click="handleAdd">新增</px-button>
      <px-button v-has="'ALL_KNOWLEDGE_CERTIFICATEMANAGE_CERTIFICATE_DOWNLOAD_TEMPLATE'" type="primary" plain @click="handleDownloadTemplate"
        >下载模板</px-button
      >
      <px-upload action="#" :http-request="handleImport" :show-file-list="false" accept=".xlsx, xls" style="margin: 0 16px">
        <px-button v-has="'ALL_KNOWLEDGE_CERTIFICATEMANAGE_CERTIFICATE_IMPORT'" type="primary" plain>批量导入</px-button>
      </px-upload>
      <px-button v-has="'ALL_KNOWLEDGE_CERTIFICATEMANAGE_CERTIFICATE_DOWNLOAD'" type="primary" plain @click="handleExport">导出</px-button>
      <px-button v-has="'ALL_KNOWLEDGE_CERTIFICATEMANAGE_CERTIFICATE_BATCH_DELETE'" plain @click="handleBatchDelete">删除</px-button>
    </div>
    <div class="table-content">
      <px-table height="calc(100vh - 400px)" :data="tableData" size="small" border class="common-table" @selection-change="handleSelect">
        <px-table-column type="selection" width="55" />
        <px-table-column type="index" label="序号" fixed width="55" align="center" />
        <px-table-column prop="twoName" label="证照类型" min-width="120" show-overflow-tooltip />
        <px-table-column prop="threeName" label="证照名称" min-width="120" show-overflow-tooltip />
        <px-table-column prop="infoStatus" label="状态" min-width="120" show-overflow-tooltip>
          <template #default="scope">
            <span :style="{ color: colorMap[scope.row.infoStatus] }">{{ stateMap[scope.row.infoStatus] }}</span>
          </template>
        </px-table-column>
        <!-- 设备证照 -->
        <template v-if="activeTab?.certificateType === 'DEVICE'">
          <px-table-column prop="deviceName" label="设备名称" min-width="120" show-overflow-tooltip />
          <px-table-column prop="deviceCode" label="设备编码" min-width="120" show-overflow-tooltip />
        </template>

        <!-- 人员证照 -->
        <template v-if="activeTab?.certificateType === 'CERTIFICATE'">
          <px-table-column prop="holder" label="持证人员" min-width="120" show-overflow-tooltip />
          <px-table-column prop="organization" label="部门" min-width="120" show-overflow-tooltip />
          <px-table-column prop="idCard" label="身份证号" min-width="120" show-overflow-tooltip />
          <px-table-column prop="phone" label="手机号" min-width="120" show-overflow-tooltip />
        </template>

        <px-table-column prop="certificationAgency" label="颁证机构" min-width="120" show-overflow-tooltip />
        <px-table-column prop="certificationDate" label="颁证日期" min-width="120" show-overflow-tooltip />
        <px-table-column prop="certificationDateValid" label="有效期" min-width="120" show-overflow-tooltip />
        <px-table-column prop="certificationDealDate" label="办证时长(天)" min-width="160" show-overflow-tooltip />
        <px-table-column prop="updateTime" label="更新时间" min-width="140" show-overflow-tooltip />
        <px-table-column prop="updateUserName" label="更新人" min-width="120" show-overflow-tooltip />
        <px-table-column prop="createTime" label="创建时间" min-width="140" show-overflow-tooltip />
        <px-table-column prop="createUserName" label="创建人" min-width="120" show-overflow-tooltip />
        <px-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip />
        <px-table-column label="操作" width="160" fixed="right" align="center">
          <template #default="scope">
            <px-tooltip content="查看" placement="top">
              <px-button v-has="'ALL_KNOWLEDGE_CERTIFICATEMANAGE_CERTIFICATE_VIEW'" link icon="View" type="primary" @click="handleView(scope.row)" />
            </px-tooltip>
            <px-tooltip content="编辑" placement="top">
              <px-button
                v-has="'ALL_KNOWLEDGE_CERTIFICATEMANAGE_CERTIFICATE_EDIT'"
                link
                icon="EditPen"
                type="primary"
                @click="handleEdit(scope.row)"
              />
            </px-tooltip>
            <px-tooltip content="注销" placement="top">
              <px-button
                v-has="'ALL_KNOWLEDGE_CERTIFICATEMANAGE_CERTIFICATE_LOGOUT'"
                link
                icon="SwitchButton"
                type="primary"
                @click="handleDrop(scope.row)"
              />
            </px-tooltip>
            <px-tooltip content="删除" placement="top">
              <px-button
                v-has="'ALL_KNOWLEDGE_CERTIFICATEMANAGE_CERTIFICATE_DELETE'"
                link
                icon="Delete"
                type="danger"
                @click="handleDelete(scope.row)"
              />
            </px-tooltip>
          </template>
        </px-table-column>
      </px-table>
      <pagination
        v-show="total > 0"
        v-model:page="pageNum"
        v-model:limit="pageSize"
        class="table-pagination"
        :total="total"
        @pagination="handleQuery"
      />
    </div>

    <!-- 新增、编辑 -->
    <div v-if="editDialogVisible">
      <AddOrEdit
        v-model:visible="editDialogVisible"
        :title="editDialogTitle"
        :classificationList="classificationList"
        :handleType="handleType"
        :activeTab="activeTab"
        :rowData="rowData"
        :classCode="classCode"
        @saveAction="handleQuery"
      />
    </div>

    <!-- 查看 -->
    <div v-if="viewDialogVisible">
      <View v-model:visible="viewDialogVisible" :activeTab="activeTab" :className="className" :rowData="rowData" />
    </div>
  </div>
</template>

<script setup>
import { queryCurrentClassList } from "@/api/common";
import {
  batchDelLicenceAPI,
  getSelectListAPI,
  certificateInfoListAPI,
  deleteCertificateInfoAPI,
  updateCertificateInfoListAPI,
  importDataAPI,
  delCertificateBatch
} from "@/api/knowledge/certificate";
import { PxMessage, PxMessageBox } from "px-ui";
import { onMounted, reactive, ref, toRefs, getCurrentInstance } from "vue";
import AddOrEdit from "./component/AddOrEdit.vue";
import View from "./component/View.vue";
import CustomTabs from "@/components/Tabs/index.vue";

defineOptions({
  name: "ALL_KNOWLEDGE_CERTIFICATEMANAGE_CERTIFICATE"
});

const { proxy } = getCurrentInstance();

const formRef = ref(null);

const state = reactive({
  tabList: [],
  queryParams: {
    twoCode: "",
    threeCode: "",
    status: ""
  },
  classCode: "MACHINE",
  className: "",
  classNameList: [],
  classificationList: [],
  nameList: [],
  loading: false,
  tableData: [],
  total: 1,
  pageNum: 1,
  pageSize: 20,
  editDialogVisible: false,
  editDialogTitle: "",
  viewDialogVisible: false,
  handleType: "",
  activeTab: {},
  selectedTableData: [],
  rowData: {}
});
const {
  tabList,
  queryParams,
  classCode,
  className,
  classNameList,
  classificationList,
  nameList,
  loading,
  tableData,
  total,
  pageNum,
  pageSize,
  editDialogVisible,
  viewDialogVisible,
  editDialogTitle,
  handleType,
  activeTab,
  rowData
} = toRefs(state);

// 证照状态
const stateMap = {
  N: "正常",
  O: "临期",
  E: "到期",
  P: "过期",
  C: "注销"
};
// 证照颜色
const colorMap = {
  N: "#10B981",
  O: "#F59E0B",
  E: "#FF771E",
  P: "#EF4444",
  C: "#903999"
};
// 证照状态列表
const statusList = [
  {
    label: "正常",
    value: "N"
  },
  {
    label: "临期",
    value: "O"
  },
  {
    label: "到期",
    value: "E"
  },
  {
    label: "过期",
    value: "P"
  },
  {
    label: "注销",
    value: "C"
  }
];

const changeTab = tab => {
  formRef.value.resetFields();
  state.activeTab = tab;
  getClassificationList();
};

onMounted(() => {
  getClassNameSelect();
});

// 获取科室数据
const getClassNameSelect = async () => {
  try {
    const res = await queryCurrentClassList();
    if (res?.length) {
      res?.forEach(i => {
        i.label = i.itemName;
        i.name = i.itemValue;
      });
      res?.push({ label: "HSE", name: "ERC" });
      state.classNameList = res;
      let obj = res?.[0];
      state.classCode = obj?.name || "";
      state.className = obj?.label || "";
      getTabList();
    }
  } catch (error) {
    console.log(error);
  }
};

// 获取tablist
const getTabList = async () => {
  try {
    const params = {
      classCode: state.classCode,
      certificateType: "",
      parentSingleCode: "",
      level: 1
    };
    const res = await getSelectListAPI(params);
    if (res?.length) {
      state.tabList = res;
      state.activeTab = res[0];
    } else {
      state.tabList = [];
      state.activeTab = {};
    }
    getClassificationList();
  } catch (error) {
    console.log(error);
  }
};

// 获取证照分类下拉数据
const getClassificationList = async () => {
  try {
    const { certificateType, singleCode } = state.activeTab;
    let params = {
      classCode: state.classCode,
      certificateType: certificateType,
      parentSingleCode: singleCode,
      level: 2
    };
    const res = await getSelectListAPI(params);
    if (res?.length) {
      state.classificationList = res;
    } else {
      state.classificationList = [];
    }
    handleQuery();
  } catch (error) {
    console.log(error);
  }
};

// 获取证照名称下拉数据
const getNameList = async () => {
  try {
    let val = state.queryParams.twoCode;
    let obj = state.classificationList?.find(i => i.singleCode === val) || {};
    const { certificateType, singleCode } = obj;
    let params = {
      classCode: state.classCode,
      certificateType: certificateType,
      parentSingleCode: singleCode,
      level: 3
    };
    const res = await getSelectListAPI(params);
    if (res?.length) {
      state.nameList = res;
    } else {
      state.nameList = [];
    }
  } catch (error) {
    console.log(error);
  }
};

// 切换科室
const handelTabSelected = val => {
  state.classCode = val;
  getTabList();
};

// 证照类型变化
const handleTypeChange = val => {
  state.queryParams.threeCode = "";
  if (val) {
    getNameList();
  } else {
    state.nameList = [];
  }
};

// 查询
const handleQuery = async () => {
  try {
    state.loading = true;
    const { twoCode, threeCode, status } = state.queryParams;
    const params = {
      pageNum: state.pageNum,
      pageSize: state.pageSize,
      classCode: state.classCode,
      certificateType: activeTab.value?.certificateType,
      twoCode: twoCode,
      threeCode: threeCode,
      infoStatus: status
    };
    if (activeTab.value?.certificateType) {
      const res = await certificateInfoListAPI(params);
      if (res?.data?.length) {
        let data = res?.data;
        data?.forEach(i => {
          let otherInfoConfig = i?.otherInfoConfig;
          Object.keys(otherInfoConfig)?.forEach(j => {
            i[j] = otherInfoConfig[j];
          });
        });
        state.tableData = data;
        state.total = res.total;
      } else {
        state.tableData = [];
        state.total = 0;
      }
    } else {
      state.tableData = [];
      state.total = 0;
    }
  } catch (error) {
    console.log(error);
  } finally {
    state.loading = false;
  }
};

// 重置
const resetQuery = () => {
  formRef.value.resetFields();
  state.nameList = [];
  handleQuery();
};

// 表格多选
const handleSelect = val => {
  state.selectedTableData = val;
};

// 批量导入
const handleImport = async options => {
  try {
    state.loading = true;
    const { file } = options;
    const formData = new FormData();
    formData.append("classCode", state.classCode);
    formData.append("certificateType", activeTab.value?.certificateType);
    formData.append("file", file);
    await importDataAPI(formData);
    PxMessage.success("批量导入成功");
    handleQuery();
  } catch (error) {
    console.log(error);
  } finally {
    state.loading = false;
  }
};

// 新增
const handleAdd = () => {
  state.editDialogTitle = "新增";
  state.handleType = "ADD";
  state.rowData = {};
  state.editDialogVisible = true;
};

// 下载模板
const handleDownloadTemplate = () => {
  let type = activeTab.value?.certificateType;
  proxy.download("post", `/dms/api/v1/certificateInfo/downloadTemplate?certificateType=${type}`, {}, "证照导入模板.xlsx");
};

// 导出
const handleExport = () => {
  const { twoCode, name, status } = state.queryParams;
  const params = {
    classCode: state.classCode,
    certificateType: activeTab.value?.certificateType,
    typeOneCode: twoCode,
    nameTwoCode: name,
    infoStatus: status,
    idList: state.selectedTableData?.map(i => i?.id)
  };
  proxy.download("post", "/dms/api/v1/certificateInfo/exportData", params, "证照台账.xlsx");
};

// 批量删除
const handleBatchDelete = () => {
  if (state.selectedTableData.length === 0) {
    PxMessage.warning("请选择要删除的数据");
    return;
  }
  PxMessageBox.confirm("是否确定删除?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    try {
      const params = {
        ids: state.selectedTableData.map(item => item.id)
      };
      // await batchDelLicenceAPI(params);
      await delCertificateBatch(params);
      handleQuery();
      PxMessage.success("删除成功");
    } catch (error) {
      console.log(error);
    }
  });
};

// 查看
const handleView = row => {
  state.rowData = row;
  state.viewDialogVisible = true;
};

// 注销
const handleDrop = row => {
  PxMessageBox.confirm("是否注销该证照", "注销", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    try {
      const params = {
        ...row,
        classCode: state.classCode,
        infoStatus: "C"
      };
      const res = await updateCertificateInfoListAPI(params);
      if (res) {
        PxMessage.success("注销成功");
        handleQuery();
      }
    } catch (error) {
      console.log(error);
    }
  });
};

// 编辑
const handleEdit = row => {
  state.editDialogTitle = "编辑";
  state.handleType = "EDIT";
  state.rowData = row;
  state.editDialogVisible = true;
};

// 删除
const handleDelete = row => {
  PxMessageBox.confirm("是否确定删除?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    try {
      const res = await deleteCertificateInfoAPI(row.id);
      if (res) {
        PxMessage.success("删除成功");
        handleQuery();
      }
    } catch (error) {
      console.log(error);
    }
  });
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/knowledge/certificateManage/scss/common.scss");

.tab {
  display: flex;
  align-items: center;
  height: 44px;
  margin-bottom: 16px;
  // background: #f4f4f4;
  border-radius: 4px;

  .tab-item {
    height: 36px;
    padding: 0 20px;
    line-height: 36px;
    text-align: center;
    cursor: pointer;
    background: #f4f4f4;

    &:nth-child(1) {
      border-radius: 4px 0 0 4px;
    }

    &:last-child {
      border-radius: 0 4px 4px 0;
    }

    &:hover {
      color: #fff;
      background: #4089f7;
    }
  }

  .active-tab {
    color: #fff;
    background: #4089f7;
    border-radius: 4px;
    box-shadow: 0 2px 4px 0 #b5d2fe;
  }
}
</style>
